package com.share.wechat.fristpage.service.impl;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.share.common.tools.io.IOUtils;
import com.share.common.tools.json.JsonUtil;
import com.share.wechat.fristpage.entity.QiHuEntity;
import com.share.wechat.fristpage.service.QiHuService;
import io.itit.itf.okhttp.FastHttpClient;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 继承类
 * Created by yujl on 2018/1/22.
 */
@Service
public class QiHuServiceImpl implements QiHuService {
    private final Log logger = LogFactory.get();

    private static final String QI_HU_CHONG_DIN_DA_HUI = "http://140.143.49.31/api/ans2";
    /**
     * 搜狗的自动答题
     */
    private static final String QI_HU_SEARCH = "http://nb.sa.sogou.com/";

    /**
     * 手机上发送请求的头头
     */
    private static final String USER_AGENT_ON_PHONE = "Mozilla/5.0 (iPhone; CPU iPhone OS 10_2_1 like Mac OS X) AppleWebKit/602.4.6 (KHTML, like Gecko) Mobile/14D27 Sogousearch/Ios/5.9.8";




    /**
     * 返回json格式的字符串
     *
     * @param key 渠道
     * @return 返回json格式的字符串
     * @throws Exception 可能有io异常
     */
    @Override
    public String doGetQiHu(String key) throws Exception {
        InputStream inputStream = FastHttpClient.get().addHeader("User-Agent", USER_AGENT_ON_PHONE)
                .addHeader("referer", QI_HU_SEARCH).url(QI_HU_CHONG_DIN_DA_HUI).addParams("key", key).addParams("wdcallback", "jQuery").build().execute().byteStream();
        String result = IOUtils.getString(inputStream);
        return result.replaceAll(" ","").replaceAll("\\\\","");
    }

    @Override
    public List<QiHuEntity> dealAnswer(String json) {
        List<QiHuEntity> resultList = new ArrayList<>(2);
        String result1 = json.substring(json.indexOf("answers")-2,json.indexOf("null_uuid")+11).trim();
        int start = json.lastIndexOf("answers")-2;
        String temp = json.substring(start);
        String result2 = temp.substring(0,temp.length()-1).trim();
        QiHuEntity qiHuEntity1 = JsonUtil.jsonToPojo(result1, QiHuEntity.class);
        QiHuEntity qiHuEntity2 = JsonUtil.jsonToPojo(result2, QiHuEntity.class);
        resultList.add(qiHuEntity1);
        resultList.add(qiHuEntity2);
        if (logger.isDebugEnabled()){
            logger.debug("查询出的实体类对象为"+resultList);
        }


        return resultList;
    }
}
